﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace GFE.SharePoint.HelperClasses
{
    public static class GFECache
    {
        private static object _cacheSetter = new object();
        private static readonly Dictionary<string, object> CacheLockList = new Dictionary<string, object>();
        private static object GetCacheLockObject(string key)
        {
            if (CacheLockList.ContainsKey(key))
            {
                return CacheLockList[key];
            }

            lock (_cacheSetter)
            {
                if (!CacheLockList.ContainsKey(key))
                {
                    CacheLockList.Add(key, new object());
                }
                return CacheLockList[key];
            }
        }

        public static void Invalidate(string key)
        {
            HttpRuntime.Cache.Remove(key);
        }

        public static T Cache<T>(string key, TimeSpan expriationTimeout, Func<string, T> filler) where T : class
        {
            T value = HttpRuntime.Cache[key] as T;
            if (value == null)
            {
                lock (GetCacheLockObject(key))
                {
                    value = HttpRuntime.Cache[key] as T;

                    if (value == null)
                    {
                        value = filler(key);
                        if (value != null)
                        {
                            Invalidate(key);
                            HttpRuntime.Cache.Add(key, value, null, DateTime.Now.Add(expriationTimeout), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, null);
                        }
                    }
                }
            }

            return value;
        }
    }
}
